<?php

namespace App\Http\Repository;

use App\Area;

class AreaRepository
{
    private $area;

    public function __construct(Area $area)
    {
        $this->area = $area;
    }

    public function getAreasByLv()
    {
        $tmpArea = $this->area
            ->where('status', 1)
            ->select('id', 'name', 'parent', 'path')
            ->get()
            ->toArray();
        foreach ($tmpArea as $area) {
            switch (substr_count($area['path'], ',')) {
                case 1:
                    $areas['省'][] = $area;
                    break;
                case 2:
                    $areas['市'][] = $area;
                    break;
                case 3:
                    $areas['县'][] = $area;
                    break;
            }
        }

        return $areas;
    }

    //得到地区的多级分类
    public function getAreasByX()
    {
        $tmpArea = $this->area
            ->select('id', 'name', 'parent', 'path', 'domain')
            ->get()
            ->toArray();
        $area = createTree($tmpArea);

        return $area;
    }

    //经营范围分级
    public function getAreaBetweenActive()
    {
        $areas = [];
        if (!empty(config('set.web_area'))) {
            foreach (explode(',', config('set.web_area')) as $area) {
                $parent = $this->area->where('id', $area)->value('parent');
                $tmpAreas[$area] = $this->area
                    ->where('id', $area)
                    ->orWhere('path', 'like', '%,' . $area . ',%')
                    ->get()
                    ->toArray();
                $areas[$area] = createTree($tmpAreas[$area], $parent)[0];
            }
        } else {
            $parents = $this->area->where('parent', 0)->pluck('id')->toArray();
            foreach ($parents as $parent) {
                $tmpAreas[$parent] = $this->area
                    ->where('id', $parent)
                    ->orWhere('path', 'like', '%,' . $parent . ',%')
                    ->get()
                    ->toArray();
                $areas[$parent] = createTree($tmpAreas[$parent])[0];
            }
        }

        return [$areas, $tmpAreas];
    }

    //得到
}